package cn.jy.boot.security.filter;

import cn.jy.boot.security.KaptchaException;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.util.ObjectUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginKaptchaFilter extends UsernamePasswordAuthenticationFilter {

    public static final String VERITYCODE_KEY = "kaptcha";

    private String codeParameter = VERITYCODE_KEY;

    public String getCodeParameter() {
        return codeParameter;
    }

    public void setCodeParameter(String codeParameter) {
        this.codeParameter = codeParameter;
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        //判断是否是一个post请求
        if (!request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        }
        //接收验证码 判断和在session中的是否一致
        String requestCode = request.getParameter(getCodeParameter());
        String sessionCode =(String)request.getSession().getAttribute("kaptcha");
        if(!(ObjectUtils.isEmpty(requestCode)) && (!ObjectUtils.isEmpty(sessionCode)) && requestCode.equalsIgnoreCase(sessionCode)){
            //认证
            return super.attemptAuthentication(request, response);
        }
        throw new KaptchaException("验证码输入错误");
    }
}
